package club.adger.server.service.impl;

import club.adger.server.dto.${Entity}Dto;
import club.adger.server.dto.PageDto;
import club.adger.server.entity.${Entity};
import club.adger.server.mapper.${Entity}Mapper;
import club.adger.server.service.${Entity}Service;
import club.adger.server.utils.CopyUtil;
import club.adger.server.utils.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
<#list typeSet as type>
    <#if type=='Date'>
        import java.util.Date;
    </#if>
</#list>

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Adger
 * @Date: 2020/07/25/5:23
 */
@Service
public class ${Entity}ServiceImpl implements ${Entity}Service {
    @Resource
    private ${Entity}Mapper ${entity}Mapper;

    /**
     * PageDto 是分页数据传输的 实体类对象
     * @param pageDto
     * @return
     */
    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        List<${Entity}> ${entity}sList = ${entity}Mapper.selectByExample(null);
<#list fieldList as field>
    <#if field.nameHump=='sort'>
        ${entity}Example.setOrderByClause("sort asc");
    </#if>
</#list>
        PageInfo<${Entity}> ${entity}PageInfo = new PageInfo<>(${entity}sList);
        pageDto.setTotal(${entity}PageInfo.getTotal());
        List<${Entity}Dto> ${entity}DtoList = CopyUtil.copyList(${entity}sList, ${Entity}Dto.class);
        pageDto.setList(${entity}DtoList);
    }

    /**
     * 这是新增或者修改的方法 下面 private 这里是公开的方法 调用就这个方法 不管内部怎么实现的
     * @param ${entity}Dto
     */
    public void add(${Entity}Dto ${entity}Dto){
        ${Entity} ${entity} = CopyUtil.copy(${entity}Dto, ${Entity}.class);
        if(StringUtils.isEmpty(${entity}Dto.getId())){
            this.insert(${entity});
        }else{
            this.update(${entity});
        }
    }

    /**
     * 这里都是private
     * 这是添加的方法
     * @param ${entity}
     */
    private void insert(${Entity} ${entity}){
    Date now = new Date();
    <#list fieldList as field>
        <#if field.nameHump=='createdAt'>
            ${entity}.setCreatedAt(now);
        </#if>
        <#if field.nameHump=='updatedAt'>
            ${entity}.setUpdatedAt(now);
        </#if>
    </#list>
        ${entity}.setId(UuidUtil.getShortUuid());
        ${entity}Mapper.insert(${entity});
    }

    /**
     * 这里也是private 这是修改的方法
     * @param ${entity}
     */
    private void update(${Entity} ${entity}){
    <#list fieldList as field>
        <#if field.nameHump=='updatedAt'>
            ${entity}.setUpdatedAt(new Date());
        </#if>
    </#list>
        ${entity}Mapper.updateByPrimaryKey(${entity});
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        ${entity}Mapper.deleteByPrimaryKey(id);
    }
}
